package com.triones.yjj.service.payment.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.io.IoUtil;
import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.config.YjjExternalAuthConfig;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.Const;
import com.ruoyi.common.utils.DateUtil;
import com.ruoyi.common.utils.SnCreator;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.mapper.SysUserMapper;
import com.ruoyi.system.service.ISysConfigService;
import com.sun.org.apache.bcel.internal.generic.NEW;
import com.triones.biz.infra.controller.enums.SceneEnum;
import com.triones.biz.infra.entity.file.FileConfigDO;
import com.triones.biz.infra.entity.file.FileDO;
import com.triones.biz.infra.entity.file.vo.FileConfigVO;
import com.triones.biz.infra.entity.file.vo.FileVO;
import com.triones.biz.infra.mapper.file.FileConfigMapper;
import com.triones.biz.infra.service.file.FileConfigService;
import com.triones.biz.infra.service.file.FileService;
import com.triones.framework.common.util.StringUtil;
import com.triones.framework.common.util.file.FileUtils;
import com.triones.framework.common.util.weixin.WeixinUtil;
import com.triones.framework.file.core.client.FileClient;
import com.triones.framework.file.core.client.FileClientConfig;
import com.triones.framework.file.core.client.local.LocalFileClientConfig;
import com.triones.framework.file.core.util.FileTypeUtils;
import com.triones.yjj.entity.*;
import com.triones.yjj.entity.bo.MemberGroupPurchaseBO;
import com.triones.yjj.entity.vo.*;
import com.triones.yjj.entity.weixin.WeixinPayConfig;
import com.triones.yjj.entity.weixin.vo.PayBill;
import com.triones.yjj.mapper.*;
import com.triones.yjj.service.GroupPurchaseGoodsItemService;
import com.triones.yjj.service.MemberActivityRelateService;
import com.triones.yjj.service.MemberGroupPurchaseService;
import com.triones.yjj.service.OrderService;
import com.triones.yjj.service.payment.PaymentManager;
import lombok.RequiredArgsConstructor;
import lombok.Synchronized;
import org.dom4j.Document;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.*;

/**
 * @author cww
 * @version 1.0
 * 2024/7/17 14:10
 */
@Service
@RequiredArgsConstructor
public class PaymentManagerImpl implements PaymentManager {
    private final Logger logger = LoggerFactory.getLogger(getClass());

    private final YjjExternalAuthConfig yjjExternalAuthConfig;

    private final OrderMapper orderMapper;

    private final ActivityMapper activityMapper;

    private final MemberGroupPurchaseMapper memberGroupPurchaseMapper;

    private final MemberGroupPurchaseItemMapper memberGroupPurchaseItemMapper;
    private final GroupPurchaseGoodsItemMapper groupPurchaseGoodsItemMapper;

    private final InviteRewardMapper inviteRewardMapper;

    private final ShareMapper shareMapper;

    private final ActivityPrizeMapper activityPrizeMapper;

    private final RuoYiConfig ruoYiConfig;
    private final FileConfigMapper fileConfigMapper;

    private final MemberActivityRelateService memberActivityRelateService;

    private final OrderTradeRecordMapper orderTradeRecordMapper;

    private final PaymentBillMapper paymentBillMapper;

    private final MemberMapper memberMapper;

    private final ShareRecordMapper shareRecordMapper;

    private final MemberDistributionRecordMapper memberDistributionRecordMapper;

    private final MemberBrowseMapper memberBrowseMapper;

    private final GroupPurchaseGoodsMapper groupPurchaseGoodsMapper;

    private final MemberGroupPurchaseService memberGroupPurchaseService;

    private final SysUserMapper baseMapper;

    private final OrderService orderService;

    private final FileService fileService;

    @Autowired
    private ISysConfigService sysConfigService;

    @Transactional(rollbackFor = Exception.class)
    public Map createOrder(WxOrderParam param) {
        //保存订单
        PayBill bill = add(param);
        bill.setOpenId(param.getOpenId());
//        payCallback(bill.getBillSn());
//        return null;
        return onPay(bill);
    }

    private PayBill add(WxOrderParam paymentBill) {
        String orderNo = StringUtil.createSn(1);
        OrderDO orderDO = new OrderDO();
        orderDO.setOrderNo(orderNo);
        orderDO.setMemberId(paymentBill.getMemberId());
        orderDO.setMemberWxUserId(paymentBill.getMemberWxUserId());
        orderDO.setActivityId(paymentBill.getActivityId());
        orderDO.setActivityTitle(paymentBill.getActivityTitle());
        orderDO.setGroupPurchaseGoodsId(paymentBill.getGroupPurchaseGoodsId());
        orderDO.setGroupPurchaseGoodsItemId(paymentBill.getGroupPurchaseGoodsItemId());
        orderDO.setGroupPurchaseGoodsNumber(1);
        orderDO.setEnrollName(paymentBill.getEnrollName());
        orderDO.setEnrollMobile(paymentBill.getEnrollMobile());
        orderDO.setEnrollOther(paymentBill.getEnrollOther());
        orderDO.setAmountTotal(paymentBill.getAmountTotal());
        //活动分销金额 是否开启分销
        orderDO.setOneDistributionAmount(BigDecimal.ZERO);//分销金额（一级）
        orderDO.setTwoDistributionAmount(BigDecimal.ZERO);//分销金额（二级）
        orderDO.setPerformanceStaffId(paymentBill.getPerformanceStaffId()); //绩效归属员工id
        orderDO.setStaffWxUserId(paymentBill.getStaffWxUserId());  //绩效归属员工微信id
        orderDO.setStaffRewardAmount(BigDecimal.ZERO); //员工奖励
        orderDO.setRebateAmount(BigDecimal.ZERO); //返利
        orderDO.setCommission(BigDecimal.ZERO);//手续费 1%
        orderDO.setRealityPayAmount(paymentBill.getAmountTotal());//实际支付金额
        orderDO.setCollectionChannel(2);//收款渠道 商家岛渠道
        orderDO.setCollectionMiniApp(1);//收款小程序
        orderDO.setStatus(1);//订单状态
        orderDO.setSettlementStatus(1);//结算状态 1：待结算、2：已结算
        orderDO.setCreateTime(new Date());
        orderDO.setUserId(paymentBill.getUserId());
        orderDO.setGroupPurchaseId(paymentBill.getGroupPurchaseId());//参与的团id
        orderDO.setShareId(paymentBill.getShareId());
        orderDO.setShareRecordId(paymentBill.getShareRecordId());//点击的分享记录id
        orderDO.setOrderSource(1);//订单来源
        orderDO.setOptionalIdentity(paymentBill.getOptionalIdentity());//自选身份（新客:new_member / 老客：old_member
        orderMapper.insert(orderDO);
        //修改客户活动关联中的最新订单号
        memberActivityRelateService.updateMemberActivityOrderId(paymentBill.getMemberId(), paymentBill.getActivityId(), orderDO.getId());
        /**
         * 创建订单交易记录
         */
        PaymentBillDO paymentBillDO = new PaymentBillDO();
        paymentBillDO.setBillSn(SnCreator.getBillSn());
        paymentBillDO.setOrderNo(orderNo);
        paymentBillDO.setIsPay(0);
        paymentBillDO.setTradePrice(paymentBill.getAmountTotal());
        paymentBillDO.setUserId(paymentBill.getUserId());
        paymentBillMapper.insert(paymentBillDO);

        PayBill payBill = new PayBill();
        payBill.setBillSn(orderNo);
        payBill.setOrderPrice(paymentBill.getAmountTotal().doubleValue());
        payBill.setSubSn(orderNo);
        return payBill;
    }

    public synchronized void payCallback(String orderNo) {
        //查询订单详情
        OrderDO orderDO = getOrderByNo(orderNo);
        /**
         * 获取商家信息
         */
        SysUser sysUser = baseMapper.selectVoById(orderDO.getUserId());
        if (sysUser == null) {
            throw new ServiceException("没有查询到商家信息");
        }
        if (ObjectUtil.isNotEmpty(orderDO)) {
            //查询活动详情（获取分销信息）
            ActivityDO activityDO = activityMapper.selectById(orderDO.getActivityId());
            if (ObjectUtil.isEmpty(activityDO)) {
                throw new ServiceException("活动不存在!");
            }
            MemberGroupPurchaseVO memberGroupPurchaseVO = memberGroupPurchaseMapper.selectVoById(orderDO.getGroupPurchaseId());
            if (ObjectUtil.isNotEmpty(memberGroupPurchaseVO)) {
                //判断团是否已满（多人同时参团）
                //最大参与参团人数 ||!groupIsFull(memberGroupPurchaseVO.getId(),memberGroupPurchaseVO.getGroupPurchaseGoodsId())
                if(memberGroupPurchaseVO.getStatus().intValue()==3){//满团
                    //查询商品
                    GroupPurchaseGoodsVO groupPurchaseGoodsVO = groupPurchaseGoodsMapper.selectVoById(orderDO.getGroupPurchaseGoodsId());
                    if (ObjectUtil.isEmpty(groupPurchaseGoodsVO)) {
                        throw new ServiceException("商品不存在！");
                    }
                    //查询一阶梯
                    GroupPurchaseGoodsItemVO groupPurchaseGoodsItemVO =getGroupPurchaseGoodsItemInfo(orderDO.getGroupPurchaseGoodsId(),1);
                    if (ObjectUtil.isEmpty(groupPurchaseGoodsItemVO)) {
                        throw new ServiceException("商品不存在!");
                    }
                    //创建团信息
                    MemberGroupPurchaseBO memberGroupPurchaseBO = new MemberGroupPurchaseBO();
                    memberGroupPurchaseBO.setTeamName(orderDO.getEnrollName());
                    memberGroupPurchaseBO.setMemberId(orderDO.getMemberId());
                    memberGroupPurchaseBO.setMemberWxUserId(orderDO.getMemberWxUserId());
                    memberGroupPurchaseBO.setMaxPersonnelNumber(groupPurchaseGoodsItemVO.getConstituteNumber());
                    memberGroupPurchaseBO.setNature(groupPurchaseGoodsVO.getNature());
                    memberGroupPurchaseBO.setActivityId(orderDO.getActivityId());
                    memberGroupPurchaseBO.setGroupPurchaseGoodsId(orderDO.getGroupPurchaseGoodsId());
                    memberGroupPurchaseBO.setGroupPurchaseGoodsItemId(groupPurchaseGoodsItemVO.getId());
                    memberGroupPurchaseBO.setUserId(orderDO.getUserId());
                    long memberGroupPurchaseId = memberGroupPurchaseService.createMemberGroupPurchase(memberGroupPurchaseBO);
                    orderDO.setGroupPurchaseId(memberGroupPurchaseId);
                    memberGroupPurchaseVO = memberGroupPurchaseMapper.selectVoById(memberGroupPurchaseId);
                }
                //创建团内信息
                MemberGroupPurchaseItemDO purchaseItemDO = new MemberGroupPurchaseItemDO();
                purchaseItemDO.setGroupPurchaseId(orderDO.getGroupPurchaseId());
                purchaseItemDO.setMemberId(orderDO.getMemberId());
                purchaseItemDO.setMemberWxUserId(orderDO.getMemberWxUserId());
                purchaseItemDO.setRegisterName(orderDO.getEnrollName());
                purchaseItemDO.setRegisterMobile(orderDO.getEnrollMobile());
                purchaseItemDO.setIsNullify(0);
                if (memberGroupPurchaseVO.getMemberId().equals(orderDO.getMemberId())) {
                    purchaseItemDO.setIdentity(1);
                } else {
                    purchaseItemDO.setIdentity(2);
                }
                purchaseItemDO.setCreateTime(new Date());
                if (orderDO.getRealityPayAmount().doubleValue() > 0d) {
                    purchaseItemDO.setIsFreeShiping(0);
                } else {
                    purchaseItemDO.setIsFreeShiping(1);
                }
                memberGroupPurchaseItemMapper.insert(purchaseItemDO);
                orderDO.setGroupPurchaseItemId(purchaseItemDO.getId());
            }
            orderDO.setStatus(2);
            BigDecimal commission = BigDecimal.ZERO;
            //实际支付金额小于0.1元不抽取手续费
            orderDO.setExtractRate(0.00);
            Double userRate = sysUser.getRate();
            if (orderDO.getRealityPayAmount().compareTo(Convert.toBigDecimal(0.1)) == 1) {
                //手续费
                if (userRate > 0) {
                    //设置当前抽取比例
                    orderDO.setExtractRate(userRate);
                    commission = orderDO.getRealityPayAmount().multiply(Convert.toBigDecimal((userRate))).divide(Convert.toBigDecimal(1000),2,BigDecimal.ROUND_HALF_EVEN);
                }
            }
            BigDecimal totalSubAmount = new BigDecimal(0);
            orderDO.setCommission(commission);
            totalSubAmount = totalSubAmount.add(commission);
            /* `rebate_amount` decimal(10,2) DEFAULT NULL COMMENT '返利',*/

            //分销
            orderDistribution(orderDO,activityDO);

            totalSubAmount = totalSubAmount.add(orderDO.getOneDistributionAmount()).add(orderDO.getTwoDistributionAmount());

            orderDO.setActualAmount(NumberUtil.sub(orderDO.getAmountTotal(), totalSubAmount));//实收金额

            /**
             * 如果没有开启奖励配置则默认核销
             */
            HashMap map = JSONUtil.toBean(activityDO.getContent(), HashMap.class);
            if(ObjectUtil.isEmpty(map)){
                throw new SecurityException("活动内容为空");
            }
            WxInviteRewardConfigVO wxDistributionVO = JSONUtil.toBean(map.get("invite_reward_config").toString(), WxInviteRewardConfigVO.class);
            if (wxDistributionVO.getIsOpenInvite()) {
                //生成核销信息
                String verificationCode = StringUtil.createSn(2);
                orderDO.setVerificationCode(verificationCode);
                //核销码
                orderDO.setVerificationQrCode(createQr(orderDO.getId()+"", "order", orderNo));
            } else {
                orderDO.setStatus(5);
                orderDO.setSettlementStatus(2);
                orderDO.setVerificationStaffId(-1L);
                orderDO.setVerificationTime(DateUtil.getDateTimeString());
                verificationDistribution(orderDO);
                /**
                 * 给商家结算
                 */
                sysUser.setWaitSettlementAmount(sysUser.getWaitSettlementAmount().add(orderDO.getActualAmount()));
                baseMapper.updateById(sysUser);
            }

            orderMapper.updateById(orderDO);
            //团参团人数
            UpdateWrapper<MemberGroupPurchaseDO> memberGroupWrapper = new UpdateWrapper<>();
            int maxNum = memberGroupPurchaseVO.getMaxPersonnelNumber();
            int curNum = memberGroupPurchaseVO.getPersonnelNumber();
            Long group_purchase_goods_item_id = 0l;
            memberGroupWrapper.set("personnel_number", curNum + 1);
            if (maxNum < curNum + 1 && !memberGroupPurchaseVO.getGroupPurchaseGoodsItemId().equals(memberGroupPurchaseVO.getNextGroupPurchaseGoodsItemId())) {
                GroupPurchaseGoodsItemDO goodsItemDO = groupPurchaseGoodsItemMapper.selectById(memberGroupPurchaseVO.getNextGroupPurchaseGoodsItemId());
                if (ObjectUtil.isNotEmpty(goodsItemDO)) {
                    maxNum = goodsItemDO.getConstituteNumber();
                    memberGroupWrapper.set("max_personnel_number", goodsItemDO.getConstituteNumber());
                    memberGroupWrapper.set("group_purchase_goods_item_id", goodsItemDO.getId());
                    group_purchase_goods_item_id = goodsItemDO.getId();
                    memberGroupPurchaseVO.setGroupPurchaseGoodsItemId(group_purchase_goods_item_id);
                    //查询下一个阶梯
                    GroupPurchaseGoodsItemDO nextGoodsItemDO = getNextGroupPurchaseGoods(goodsItemDO.getGroupPurchaseGoodsId(), goodsItemDO.getConstituteNumber());
                    if (ObjectUtil.isNotEmpty(nextGoodsItemDO)) {
                        memberGroupWrapper.set("next_group_purchase_goods_item_id", nextGoodsItemDO.getId());
                        memberGroupPurchaseVO.setNextGroupPurchaseGoodsItemId(nextGoodsItemDO.getId());
                    } else {
                        memberGroupWrapper.set("next_group_purchase_goods_item_id", goodsItemDO.getId());
                        memberGroupPurchaseVO.setNextGroupPurchaseGoodsItemId(goodsItemDO.getId());
                    }
                }
            }
            if (memberGroupPurchaseVO.getGroupPurchaseGoodsItemId().equals(memberGroupPurchaseVO.getNextGroupPurchaseGoodsItemId()) && maxNum <= curNum + 1) {
                memberGroupWrapper.set("status", 3);
            } else {
                if (memberGroupPurchaseVO.getStatus().equals(1) && maxNum > curNum + 1) {
                    memberGroupWrapper.set("status", 1);
                } else {
                    memberGroupWrapper.set("status", 2);
                }
            }
            // 1待成团 2已成团 3已满团
            MemberGroupPurchaseDO memberGroupPurchaseDO = new MemberGroupPurchaseDO();
            //BeanUtil.copyProperties(memberGroupPurchaseVO, memberGroupPurchaseDO);
            memberGroupWrapper.eq("id", orderDO.getGroupPurchaseId());
            memberGroupPurchaseMapper.update(memberGroupPurchaseDO, memberGroupWrapper);

            //根据团修改团成员订单商品阶梯
            if(group_purchase_goods_item_id.intValue()>0){
                UpdateWrapper<OrderDO> doOrderGoodsUpdateWrapper = new UpdateWrapper<>();
                doOrderGoodsUpdateWrapper.set("group_purchase_goods_item_id",group_purchase_goods_item_id);
                doOrderGoodsUpdateWrapper.eq("group_purchase_id",orderDO.getGroupPurchaseId());
                orderMapper.update(new OrderDO(),doOrderGoodsUpdateWrapper);
            }

            //报名成功新增邀请
            WxInviteRewardConfigVO wxInviteRewardConfigVO = getContentInviteRewardConfig(activityDO.getContent());
            if (ObjectUtil.isNotEmpty(wxInviteRewardConfigVO)) {
                if (wxInviteRewardConfigVO.getIsOpenInvite()) {
                    if ("ruleA".equals(wxInviteRewardConfigVO.getComputeWay())) {
                        saveOrUpdateInviteReward(orderDO);
                    }
                }
            }
            // 带来的购买人数  带来的购买次数  带来的总的支付金额 tr_share
            setShareData(orderDO);
        }
        // 更新资金记录
//        OrderTradeRecordDO amountTradeRecord = new OrderTradeRecordDO();
//        amountTradeRecord.setOrderId(orderDO.getId());
//        amountTradeRecord.setFundType("order_settled");
//        amountTradeRecord.setTradeAmount(orderDO.getRealityPayAmount());
//        amountTradeRecord.setMemberId(orderDO.getMemberId());
//        amountTradeRecord.setMemberWxUserId(orderDO.getMemberWxUserId());
//        amountTradeRecord.setSettlementStatus(1);
//        amountTradeRecord.setUserId(orderDO.getUserId());
//        orderTradeRecordMapper.insert(amountTradeRecord);
        // 更新累计邀请人数
        memberActivityRelateService.updateMemberActivityInviteTotal("orderPay", orderDO.getMemberId(), orderDO.getActivityId(), orderDO.getShareId());
        //更新客户信息表
        MemberDO memberDO = memberMapper.selectById(orderDO.getMemberId());
        if (ObjectUtil.isNotEmpty(memberDO)) {
            UpdateWrapper<MemberDO> memberUpdateWrapper = new UpdateWrapper<>();
            memberUpdateWrapper.eq("id", orderDO.getMemberId());
            memberUpdateWrapper.set("transaction_total_amount", Convert.toBigDecimal(memberDO.getTransactionTotalAmount(),BigDecimal.ZERO)
                .add(orderDO.getRealityPayAmount()));
            memberUpdateWrapper.set("transaction_number", memberDO.getTransactionNumber() + 1);
            memberUpdateWrapper.set("lately_transaction_time", DateUtil.getDateTimeString());
            memberUpdateWrapper.set("lately_order_name", orderDO.getEnrollName());
            memberUpdateWrapper.set("lately_order_mobile", orderDO.getEnrollMobile());
            memberMapper.update(new MemberDO(), memberUpdateWrapper);
        }
        //客户浏览表
        updateMemberBrowse(orderDO);
        //客户分享表更新
        updateShare(orderDO.getMemberId(),orderDO.getActivityId());
    }

    private void updateShare(Long memberId,Long activityId){
        QueryWrapper<ShareDO> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("member_id", memberId);
        queryWrapper.eq("product_id", activityId);
        queryWrapper.eq("product_type", 1);
        queryWrapper.last(" LIMIT 1");
        ShareDO shareDO =  shareMapper.selectOne(queryWrapper);
        if (ObjectUtil.isNotEmpty(shareDO)&&shareDO.getEnrollStatus().intValue()==2) {
            shareDO.setEnrollStatus(1);
            shareMapper.updateById(shareDO);
        }
    }
    private void updateMemberBrowse(OrderDO orderDO) {
        QueryWrapper<MemberBrowseDO> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("member_id", orderDO.getMemberId());
        queryWrapper.eq("product_id", orderDO.getActivityId());
        queryWrapper.eq("product_type", 1);//产品类型  1活动 2商品
        queryWrapper.last(" LIMIT 1");
        MemberBrowseDO memberBrowseDO = memberBrowseMapper.selectOne(queryWrapper);
        if (ObjectUtil.isNotEmpty(memberBrowseDO)) {
            memberBrowseDO.setEnrollStatus(1);
            memberBrowseMapper.updateById(memberBrowseDO);
        }
    }

    private void orderDistribution(OrderDO orderDO,ActivityDO activityDO ) {
        /**
         * 分销计算
         */
        List<MemberDistributionRecordDO> memberDistributionRecordList = new ArrayList<>();
        WxDistributionVO wxDistributionVO = getContentDistribution(activityDO.getContent());
        if (ObjectUtil.isNotEmpty(wxDistributionVO)) {
            //是否开启分销
            if (wxDistributionVO.getIsOpenDistribution()) {
                String distributionRule = wxDistributionVO.getDistributionRule();
                if ("ruleA".equals(distributionRule)) {
                    //查询第一级邀请人是否已购买
                    if (orderDO.getShareId() != null && orderDO.getShareId() != 0) {
                        ShareDO shareDO = shareMapper.selectById(orderDO.getShareId());
                        if (shareDO != null) {
                            if (getMemberBuy(shareDO.getId())) {
                                double oneDistributionAmount = randomBetweenTwoValues(wxDistributionVO.getOneDistributionAmount());
                                MemberDistributionRecordDO memberDistributionRecordDO = new MemberDistributionRecordDO();
                                memberDistributionRecordDO.setActivityId(orderDO.getActivityId());
                                memberDistributionRecordDO.setDistributionGrade(1);
                                memberDistributionRecordDO.setMemberId(shareDO.getMemberId());
                                memberDistributionRecordDO.setMemberWxUserId(shareDO.getMemberWxUserId());
                                memberDistributionRecordDO.setThirdMemberId(orderDO.getMemberId());
                                memberDistributionRecordDO.setThirdMemberWxUserId(orderDO.getMemberWxUserId());
                                memberDistributionRecordDO.setThirdPlaceOrderId(orderDO.getId());
                                memberDistributionRecordDO.setKickback(Convert.toBigDecimal(oneDistributionAmount));
                                memberDistributionRecordDO.setUserId(orderDO.getUserId());
                                memberDistributionRecordDO.setUpLevelMemberId(0l);
                                memberDistributionRecordDO.setUpLevelMemberWxUserId(0l);
                                memberDistributionRecordList.add(memberDistributionRecordDO);
                                orderDO.setOneDistributionAmount(Convert.toBigDecimal(oneDistributionAmount));

                                this.updateMemberDistribution(shareDO.getMemberId(),Convert.toBigDecimal(oneDistributionAmount));
                            }
                            if (orderDO.getShareRecordId() != null && orderDO.getShareRecordId() != 0) {
                                WxShareRecordVO twoShareRecordVO = shareRecordMapper.getShareRecordInfo(orderDO.getShareRecordId());
                                if (twoShareRecordVO != null) {
                                    WxShareRecordVO recordMapperShareRecordInfo = shareRecordMapper.getShareRecordInfo(twoShareRecordVO.getPreviousShareRecordId());
                                    if (recordMapperShareRecordInfo != null) {
                                        if (getMemberBuy(recordMapperShareRecordInfo.getShareId())) {
                                            double twoDistributionAmount = randomBetweenTwoValues(wxDistributionVO.getTwoDistributionAmount());
                                            MemberDistributionRecordDO memberDistributionRecordDO = new MemberDistributionRecordDO();
                                            memberDistributionRecordDO.setActivityId(orderDO.getActivityId());
                                            memberDistributionRecordDO.setDistributionGrade(2);
                                            memberDistributionRecordDO.setMemberId(recordMapperShareRecordInfo.getMemberId());
                                            memberDistributionRecordDO.setMemberWxUserId(recordMapperShareRecordInfo.getMemberWxUserId());
                                            memberDistributionRecordDO.setThirdMemberId(orderDO.getMemberId());
                                            memberDistributionRecordDO.setThirdMemberWxUserId(orderDO.getMemberWxUserId());
                                            memberDistributionRecordDO.setThirdPlaceOrderId(orderDO.getId());
                                            memberDistributionRecordDO.setKickback(Convert.toBigDecimal(twoDistributionAmount));
                                            memberDistributionRecordDO.setUserId(orderDO.getUserId());
                                            memberDistributionRecordDO.setUpLevelMemberId(shareDO.getMemberId());
                                            memberDistributionRecordDO.setUpLevelMemberWxUserId(shareDO.getMemberWxUserId());
                                            memberDistributionRecordList.add(memberDistributionRecordDO);
                                            orderDO.setTwoDistributionAmount(Convert.toBigDecimal(Convert.toBigDecimal(twoDistributionAmount)));

                                            this.updateMemberDistribution(recordMapperShareRecordInfo.getMemberId(),Convert.toBigDecimal(twoDistributionAmount));
                                        }
                                    }
                                }
                            }
                        }
                    }
                } else if ("ruleB".equals(distributionRule)) {
                    //查询第一级邀请人是否已购买
                    if (orderDO.getShareId() != null && orderDO.getShareId() != 0) {
                        ShareDO shareDO = shareMapper.selectById(orderDO.getShareId());
                        if (shareDO != null) {
                            double oneDistributionAmount = randomBetweenTwoValues(wxDistributionVO.getOneDistributionAmount());
                            MemberDistributionRecordDO memberDistributionRecordDO = new MemberDistributionRecordDO();
                            memberDistributionRecordDO.setActivityId(orderDO.getActivityId());
                            memberDistributionRecordDO.setDistributionGrade(1);
                            memberDistributionRecordDO.setMemberId(shareDO.getMemberId());
                            memberDistributionRecordDO.setMemberWxUserId(shareDO.getMemberWxUserId());
                            memberDistributionRecordDO.setThirdMemberId(orderDO.getMemberId());
                            memberDistributionRecordDO.setThirdMemberWxUserId(orderDO.getMemberWxUserId());
                            memberDistributionRecordDO.setThirdPlaceOrderId(orderDO.getId());
                            memberDistributionRecordDO.setKickback(Convert.toBigDecimal(oneDistributionAmount));
                            memberDistributionRecordDO.setUserId(orderDO.getUserId());
                            memberDistributionRecordDO.setUpLevelMemberId(0l);
                            memberDistributionRecordDO.setUpLevelMemberWxUserId(0l);
                            memberDistributionRecordList.add(memberDistributionRecordDO);
                            orderDO.setOneDistributionAmount(Convert.toBigDecimal(oneDistributionAmount));
                            this.updateMemberDistribution(shareDO.getMemberId(),Convert.toBigDecimal(oneDistributionAmount));

                            if (orderDO.getShareRecordId() != null && orderDO.getShareRecordId() != 0) {
                                WxShareRecordVO twoShareRecordVO = shareRecordMapper.getShareRecordInfo(orderDO.getShareRecordId());
                                if (twoShareRecordVO != null) {
                                    WxShareRecordVO recordMapperShareRecordInfo = shareRecordMapper.getShareRecordInfo(twoShareRecordVO.getPreviousShareRecordId());
                                    if (recordMapperShareRecordInfo != null) {
                                        double twoDistributionAmount = randomBetweenTwoValues(wxDistributionVO.getTwoDistributionAmount());
                                        MemberDistributionRecordDO twomemberDistributionRecordDO = new MemberDistributionRecordDO();
                                        twomemberDistributionRecordDO.setActivityId(orderDO.getActivityId());
                                        twomemberDistributionRecordDO.setDistributionGrade(2);
                                        twomemberDistributionRecordDO.setMemberId(recordMapperShareRecordInfo.getMemberId());
                                        twomemberDistributionRecordDO.setMemberWxUserId(recordMapperShareRecordInfo.getMemberWxUserId());
                                        twomemberDistributionRecordDO.setThirdMemberId(orderDO.getMemberId());
                                        twomemberDistributionRecordDO.setThirdMemberWxUserId(orderDO.getMemberWxUserId());
                                        twomemberDistributionRecordDO.setThirdPlaceOrderId(orderDO.getId());
                                        twomemberDistributionRecordDO.setKickback(Convert.toBigDecimal(twoDistributionAmount));
                                        twomemberDistributionRecordDO.setUserId(orderDO.getUserId());
                                        memberDistributionRecordDO.setUpLevelMemberId(shareDO.getMemberId());
                                        memberDistributionRecordDO.setUpLevelMemberWxUserId(shareDO.getMemberWxUserId());
                                        memberDistributionRecordList.add(twomemberDistributionRecordDO);
                                        orderDO.setTwoDistributionAmount(Convert.toBigDecimal(Convert.toBigDecimal(twoDistributionAmount)));
                                        this.updateMemberDistribution(recordMapperShareRecordInfo.getMemberId(),Convert.toBigDecimal(twoDistributionAmount));
                                    }
                                }
                            }
                        }
                    }
                }
                if (memberDistributionRecordList.size() > 0) {
                    memberDistributionRecordMapper.insertBatch(memberDistributionRecordList);
                }
            }
        }
    }

    private Double randomBetweenTwoValues(WxDistributionAmountValueVO vo) {
        Double bNum = 100D;//double转整数
        Double min = NumberUtil.mul(vo.getMin(), bNum);
        Double max = NumberUtil.mul(vo.getMax(), bNum);
        if (min.equals(max)) {
            return vo.getMin();
        }
        // 创建Random实例
        Random random = new Random();
        // 获取两数值之间的随机值
        int randomValue = random.nextInt(max.intValue() - min.intValue() + 1) + min.intValue();
        return NumberUtil.div(randomValue, 100);
    }

    private boolean getMemberBuy(Long shareId) {
        ShareDO shareDO = shareMapper.selectById(shareId);
        if (ObjectUtil.isNotEmpty(shareDO)) {
            QueryWrapper<OrderDO> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("member_id", shareDO.getMemberId());
            queryWrapper.eq("activity_id", shareDO.getProductId());
            queryWrapper.eq("user_id", shareDO.getUserId());
            queryWrapper.in("status", 2, 5);
            return orderMapper.selectCount(queryWrapper) > 0;
        } else {
            return false;
        }
    }

    /**
     * 获取活动分销配置
     *
     * @param content
     * @return
     */
    private WxDistributionVO getContentDistribution(String content) {
        HashMap map = JSONUtil.toBean(content, HashMap.class);
        if (ObjectUtil.isNotEmpty(map)) {
            WxDistributionVO wxDistributionVO = JSONUtil.toBean(map.get("open_distribution_config").toString(), WxDistributionVO.class);
            return wxDistributionVO;
        }
        return null;
    }

    /**
     * 获取活动邀请成功配置
     *
     * @param content
     * @return
     */
    private WxInviteRewardConfigVO getContentInviteRewardConfig(String content) {
        HashMap map = JSONUtil.toBean(content, HashMap.class);
        if (ObjectUtil.isNotEmpty(map)) {
            WxInviteRewardConfigVO wxDistributionVO = JSONUtil.toBean(map.get("invite_reward_config").toString(), WxInviteRewardConfigVO.class);
            return wxDistributionVO;
        }
        return null;
    }

    private void setShareData(OrderDO orderDO) {
        ShareDO shareDO = shareMapper.selectById(orderDO.getShareId());
        if (ObjectUtil.isNotEmpty(shareDO)) {
         /*
               `enroll_status` int(2) DEFAULT NULL COMMENT '报名状态',
              */
            UpdateWrapper<ShareDO> updateWrapper = new UpdateWrapper<>();
            // 用户是否已买过
            QueryWrapper<OrderDO> orderDOQueryWrapper = new QueryWrapper<>();
            orderDOQueryWrapper.eq("activity_id", orderDO.getActivityId());
            orderDOQueryWrapper.eq("member_id", orderDO.getMemberId());
            orderDOQueryWrapper.eq("user_id", orderDO.getUserId());
            orderDOQueryWrapper.in("status", 2, 5);
            Long count = orderMapper.selectCount(orderDOQueryWrapper);
            if (count == 1) {
                updateWrapper.set("member_buy_number", shareDO.getMemberBuyNumber() + 1);
            }
            updateWrapper.set("buy_number", shareDO.getBuyNumber() + 1);
            updateWrapper.set("pay_total", NumberUtil.add(shareDO.getPayTotal(), orderDO.getActualAmount()));
            updateWrapper.eq("id", shareDO.getId());
            shareMapper.update(shareDO, updateWrapper);
        }
    }

    public GroupPurchaseGoodsItemDO getNextGroupPurchaseGoods(Long goodsId, int constituteNumber) {
        QueryWrapper<GroupPurchaseGoodsItemDO> wrapper = new QueryWrapper<>();
        wrapper.gt("constitute_number", constituteNumber);
        wrapper.eq("group_purchase_goods_id", goodsId);
        wrapper.last(" LIMIT 1");
        wrapper.orderByAsc("constitute_number");
        return groupPurchaseGoodsItemMapper.selectOne(wrapper);
    }

    public OrderDO getOrderByNo(String orderNo) {
        QueryWrapper<OrderDO> wrapper = new QueryWrapper<>();
        wrapper.eq("order_no", orderNo);
        return orderMapper.selectOne(wrapper);
    }

    /**
     * 支付
     *
     * @param bill
     * @return
     */
    private Map onPay(PayBill bill) {
        Map<String, String> params = new TreeMap<>();
        Map<String, String> resultMap = new TreeMap<>();
        params.put("spbill_create_ip", "0:0:0:0:0:0:0:1");
        params.put("trade_type", "JSAPI");

        String openid = bill.getOpenId();

        params.put("openid", openid);

        String result = "";

        try {

            Map<String, String> map = createUnifiedOrder(bill, params);

            // 返回结果
            String returnCode = map.get("return_code");
            logger.debug("微信支付返回结果：" + returnCode);
            if ("SUCCESS".equals(returnCode)) {
                // 业务码
                String resultCode = map.get("result_code");

                if ("SUCCESS".equals(resultCode)) {
                    // 预支付订单id
                    String prepayId = map.get("prepay_id");
                    logger.debug("微信支付id：" + prepayId);
                    Map<String, String> weixinparams = new TreeMap();
                    weixinparams.put("appId", map.get("appid"));
                    weixinparams.put("nonceStr", StringUtil.getRandStr(10));
                    weixinparams.put("timeStamp", String.valueOf(DateUtil.getDateline()));
                    weixinparams.put("package", "prepay_id=" + prepayId);
                    weixinparams.put("signType", "MD5");
                    String sign = WeixinUtil.createSign(weixinparams, yjjExternalAuthConfig.getKey());
                    weixinparams.put("paySign", sign);
                    resultMap = weixinparams;
                    //String outTradeNo = bill.getBillSn();
                    logger.debug("微信返回map：" + weixinparams);
                    //  resultReturnMap = getPayMap(prepayId,map.get("appid"), map.get("key"));
                    //result = this.getPayScript(prepayId, map.get("appid"), map.get("key"), outTradeNo, bill.getTradeType());
                    logger.debug("微信返回结果：" + result);
                } else {
                    String errCode = map.get("err_code");
                    String errCodeDes = map.get("err_code_des");
                    result = "<script>alert('支付意外错误，请联系技术人员:"
                        + errCode + "【" + errCodeDes + "】')</script>";
                    logger.error(result);
                }
            } else {
                result = "<script>alert('支付意外错误，请联系技术人员:" + returnCode + "')</script>";
                if ("FAIL".equals(returnCode)) {
                    // 错误信息
                    String returnMsg = map.get("return_msg");
                    this.logger.error("微信端返回错误" + returnCode + "[" + returnMsg + "]");
                }
            }
        } catch (Exception e) {
            this.logger.error("微信生成支付二维码错误", e);
            return null;
        }

        // resultMap.put("gateway_url",result);
        // logger.debug(resultMap);
        return resultMap;

    }

    /**
     * 组装参数生成预付订单
     *
     * @param bill
     * @param params
     * @return 微信返回信息和支付参数
     */
    protected Map<String, String> createUnifiedOrder(PayBill bill, Map<String, String> params) {
        Map<String, String> map = new HashMap<>();
        WeixinPayConfig config = new WeixinPayConfig();
        config.setAppId(yjjExternalAuthConfig.getAppid());
        config.setMchId(yjjExternalAuthConfig.getMchid());
        config.setKey(yjjExternalAuthConfig.getKey());

        params.put("appid", config.getAppId());
        params.put("mch_id", config.getMchId());
        params.put("nonce_str", StringUtil.getRandStr(10));
        params.put("body", "YJJ-" + bill.getSubSn());
        params.put("out_trade_no", bill.getBillSn());
        // 应付转为分
        Double money = bill.getOrderPrice();
        if (money != null) {
            params.put("total_fee", StringUtil.toFen(money));
//            params.put("total_fee", "1");
        }
        String notifyUrl = yjjExternalAuthConfig.getNotifyUrl();
        params.put("notify_url", notifyUrl);
        logger.info("微信回调地址：" + notifyUrl);

        String sign = WeixinUtil.createSign(params, config.getKey());
        params.put("sign", sign);
        try {
            String xml = WeixinUtil.mapToXml(params);

            logger.debug("微信支付请求参数如下：");
            logger.debug(xml);

            Document resultDoc = WeixinUtil.post("https://api.mch.weixin.qq.com/pay/unifiedorder", xml);


            //Element rootEl = resultDoc.getRootElement();

            Map resultMap = WeixinUtil.xmlToMap(resultDoc);
            xml = WeixinUtil.mapToXml(resultMap);

            logger.debug("微信返回值为：");
            logger.debug(xml);

            resultMap.putAll(map);

            return resultMap;
        } catch (Exception e) {
            this.logger.error("生成参数失败", e);
        }

        return null;
    }

    /**
     * 生成支付的脚本
     *
     * @param prepayId
     * @param appid
     * @param weixinkey
     * @return
     */
    private Map<String, String> getPayMap(String prepayId, String appid, String weixinkey) {

        Map<String, String> params = new TreeMap();
        params.put("appId", appid);
        params.put("nonceStr", StringUtil.getRandStr(10));
        params.put("timestamp", String.valueOf(DateUtil.getDateline()));
        params.put("package", "prepay_id=" + prepayId);
        params.put("signType", "MD5");
        String sign = WeixinUtil.createSign(params, weixinkey);
        params.put("paySign", sign);
        return params;
    }

    /**
     * 生成支付的脚本
     *
     * @param prepayId
     * @param appid
     * @param weixinkey
     * @param outTradeNo
     * @return
     */
    private String getPayScript(String prepayId, String appid, String weixinkey, String outTradeNo) {

        Map<String, String> params = new TreeMap();
        params.put("appId", appid);
        params.put("nonceStr", StringUtil.getRandStr(10));
        params.put("timestamp", String.valueOf(DateUtil.getDateline()));
        params.put("package", "prepay_id=" + prepayId);
        params.put("signType", "MD5");
        String sign = WeixinUtil.createSign(params, weixinkey);
        params.put("paySign", sign);


        StringBuffer payStr = new StringBuffer();
        payStr.append("WeixinJSBridge.invoke('getBrandWCPayRequest',{");

        int i = 0;
        for (String key : params.keySet()) {
            String value = params.get(key);

            if (i != 0) {
                payStr.append(",");
            }

            payStr.append("'" + key + "':'" + value + "'");
            i++;

        }

        payStr.append("}");

        payStr.append(",function(res){  if( 'get_brand_wcpay_request:ok'==res.err_msg ) { "
            + "alert('支付成功'); "
            + "location.href='" + getPayWapSuccessUrl(outTradeNo) + "?operation=success';"
            + "}else{ alert('支付失败'); "
            + "location.href='" + getPayWapSuccessUrl(outTradeNo) + "?operation=fail';"
            + "} "
            + "}");

        payStr.append(");");

        return payStr.toString();
    }

    /**
     * 获取支付成功调取页面
     *
     * @param outTradeNo
     * @return
     */
    private String getPayWapSuccessUrl(String outTradeNo) {

        // HttpServletRequest request = ThreadContextHolder.getHttpRequest();
        String serverName = "";
        int port = 80;
        String portstr = "";
        if (port != 80) {
            portstr = ":" + port;
        }
        String contextPath = "";
        logger.info("支付成功页面跳转：" + "http://" + serverName + portstr + contextPath + "/order_" + outTradeNo + "_payment-wap-result.html");
        return "http://" + serverName + portstr + contextPath + "/order_" + outTradeNo + "_payment-wap-result.html";
    }

    /**
     * 异步回调
     *
     * @param
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public String onCallback(Map<String, String> params) {

        Map map = new HashMap(16);
        try {
            String returnCode = params.get("return_code");
            String resultCode = params.get("result_code");
            if ("SUCCESS".equals(returnCode) && "SUCCESS".equals(resultCode)) {
                String sign = WeixinUtil.createSign(params, yjjExternalAuthConfig.getKey());
                if (sign.equals(params.get("sign"))) {

                    // 本商城交易号
                    String outTradeNo = params.get("out_trade_no");
                    // 微信支付订单号
                    String returnTradeNo = params.get("transaction_id");
                    // 支付金额
                    double payPrice = StringUtil.toDouble(params.get("total_fee"), 0d);
                    // 传回来的是分，转为元
                    payPrice = StringUtil.mul(payPrice, 0.01);
                    logger.info("支付成功:outTradeNo/returnTradeNo----->" + outTradeNo + "/" + returnTradeNo);
                    // 更新订单交易
                    LambdaQueryWrapper<PaymentBillDO> paymentBillWrapper = Wrappers.lambdaQuery(PaymentBillDO.class);
                    paymentBillWrapper.eq(PaymentBillDO::getOrderNo, outTradeNo).eq(PaymentBillDO::getIsPay, 0);
                    PaymentBillDO bill = paymentBillMapper.selectOne(paymentBillWrapper);
                    if (bill != null) {
                        bill.setIsPay(1);
                        bill.setReturnTradeNo(returnTradeNo);
                        paymentBillMapper.updateById(bill);
                    }
                    payCallback(outTradeNo);
                    map.put("return_code", "SUCCESS");
                    // 标记为成功
                } else {
                    map.put("return_code", "FAIL");
                    map.put("return_msg", "签名失败");
                    this.logger.error("微信签名失败");
                }
            } else {
                map.put("return_code", "FAIL");
                this.logger.error("微信验签失败");
            }
        } catch (Exception e) {
            map.put("return_code", "FAIL");
            map.put("return_msg", "");
            this.logger.error("微信通知的结果为失败", e);
        }
        try {
            return WeixinUtil.mapToXml(map);
        } catch (Exception e) {
            this.logger.error("微信通知的结果为失败", e);
            return "出现错误";
        }

    }

    /**
     * 查询账单状态
     *
     * @param billSn
     * @param config
     * @return
     */
    public String onQuery(String billSn, Map<String, String> config) {

        String appId = config.get("appid");
        String mchId = config.get("mchid");
        String key = config.get("key");

        Map<String, String> params = new TreeMap();
        params.put("appid", appId);
        params.put("mch_id", mchId);
        params.put("nonce_str", StringUtil.getRandStr(10));
        params.put("out_trade_no", billSn);
        String sign = WeixinUtil.createSign(params, key);
        params.put("sign", sign);

        try {
            String xml = WeixinUtil.mapToXml(params);
            Document resultDoc = WeixinUtil.post("https://api.mch.weixin.qq.com/pay/orderquery", xml);
            Map<String, String> returnParams = WeixinUtil.xmlToMap(resultDoc);

            // 返回结果
            String returnCode = returnParams.get("return_code");
            String resultCode = returnParams.get("result_code");
            String tradeState = returnParams.get("trade_state");
            if ("SUCCESS".equals(returnCode) || "SUCCESS".equals(resultCode)) {
                if ("SUCCESS".equals(tradeState)) {
                    //在这里不做更改订单状态的操作，而是在异步通知中来完成
                    //原因是：这个查询是用户体验相关的，在订单已经支付状态时（异步通知可能成功了），此处可能返回fail
                    return "SUCCESS";
                } else {
                    return "FAIL";
                }

            } else {
                return "FAIL";
            }

        } catch (Exception e) {
            e.printStackTrace();
            logger.error("微信支付查询失败", e);
            return "FAIL";
        }


    }

    private void saveOrUpdateInviteReward(OrderDO orderDO) {
        /*查询邀请人share_id*/
        ShareVO shareVO = shareMapper.selectVoById(orderDO.getShareId());
        if (ObjectUtil.isNotEmpty(shareVO)) {
            QueryWrapper<InviteRewardDO> wrapper = new QueryWrapper<>();
            wrapper.eq("activity_id", orderDO.getActivityId());
            wrapper.eq("member_id", shareVO.getMemberId());
            wrapper.eq("user_id", orderDO.getUserId());
            wrapper.eq("verification_status", 1);
            InviteRewardDO inviteRewardDO = inviteRewardMapper.selectOne(wrapper);

            if (ObjectUtil.isEmpty(inviteRewardDO)) {
                ActivityPrizeVO activityPrizeVO = getPrizeIdByNum(orderDO.getActivityId(), 1);
                if (ObjectUtil.isNotEmpty(activityPrizeVO)) {
                    inviteRewardDO = new InviteRewardDO();
                    inviteRewardDO.setActivityId(orderDO.getActivityId());
                    inviteRewardDO.setMemberId(shareVO.getMemberId());
                    inviteRewardDO.setMemberWxUserId(shareVO.getMemberWxUserId());
                    inviteRewardDO.setPrizeId(activityPrizeVO.getId());
                    if (activityPrizeVO.getRequirementInviteNumber().intValue() == 1) {
                        inviteRewardDO.setStatus(1);
                    } else {
                        inviteRewardDO.setStatus(0);
                    }
                    String verificationCode = StringUtil.createSn(3);
                    String verificationCodeQr = createQr(verificationCode, "invite_prize", shareVO.getMemberId() + "");
                    inviteRewardDO.setVerificationCode(verificationCode);
                    inviteRewardDO.setVerificationQrCode(verificationCodeQr);
                    inviteRewardDO.setVerificationStatus(1);
                    inviteRewardDO.setUserId(orderDO.getUserId());
                    inviteRewardDO.setInviteNumber(1);
                    inviteRewardMapper.insert(inviteRewardDO);
                }

            } else {
                int inviteNum = inviteRewardDO.getInviteNumber() + 1;
                ActivityPrizeVO activityPrizeVO = getPrizeIdByNum(orderDO.getActivityId(), inviteNum);
                if (ObjectUtil.isNotEmpty(activityPrizeVO)) {
                    UpdateWrapper<InviteRewardDO> updateWrapper = new UpdateWrapper<>();
                    updateWrapper.set("invite_number", inviteNum);
                    if (!inviteRewardDO.getPrizeId().equals(activityPrizeVO.getId())) {
                        //1：已达成、2：已升级
                        if (inviteNum >= activityPrizeVO.getRequirementInviteNumber()) {
                            updateWrapper.set("prize_id", activityPrizeVO.getId());
                            updateWrapper.set("status", 1);
                        } else {
                            updateWrapper.set("status", 2);
                        }
                    }
                    updateWrapper.eq("id", inviteRewardDO.getId());
                    inviteRewardMapper.update(inviteRewardDO, updateWrapper);
                }
            }
        }
    }

    private ActivityPrizeVO getPrizeIdByNum(Long activityId, int num) {
        QueryWrapper<ActivityPrizeDO> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("activity_id", activityId);
        queryWrapper.orderByAsc("requirement_invite_number");
        List<ActivityPrizeVO> list = activityPrizeMapper.selectVoList(queryWrapper);
        ActivityPrizeVO returnActivityPrizeVO = null;
        if (list != null && list.size() > 0) {
            for (ActivityPrizeVO activityPrizeVO : list) {
                if (num <= activityPrizeVO.getRequirementInviteNumber().intValue()) {
                    returnActivityPrizeVO = activityPrizeVO;
                    break;
                }
            }
        }
        return returnActivityPrizeVO;
    }

    private String createQr(String key, String type, String orderNo) {
        String basePath = sysConfigService.selectConfigByKey("sys.base.file.dir");
        if(StringUtils.isEmpty(basePath)){
            basePath = "/files";
        }
        /* QueryWrapper<FileConfigDO> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("master", 1);
        queryWrapper.eq("deleted", 0);
        queryWrapper.last(" LIMIT 1");
       FileConfigVO configVO = fileConfigMapper.selectVoOne(queryWrapper);
        LocalFileClientConfig clientConfig = (LocalFileClientConfig) configVO.getConfig();
        String basePath = clientConfig.getBasePath();*/
        String path =  ruoYiConfig.getName() + "/" + type + "/" + orderNo + "/" + "qrcode.png";
//        String domain = clientConfig.getDomain();
        String content = "";
        if("order".equals(type)){
            content = Const.STAFF_ORDER_VERIFICATION.replace("ORDERID",key).replace("TYPE","1");
//            content = Const.STAFF_ORDER_VERIFICATION.replace("ORDERID","1").replace("TYPE","1");
        }else{//invite_prize
            content = Const.STAFF_ORDER_VERIFICATION.replace("ORDERID",key).replace("TYPE","2");
//            content = Const.STAFF_ORDER_VERIFICATION.replace("ORDERID","1").replace("TYPE","2");
        }
//        StringUtil.createQr(content, basePath + path);
        File file =  StringUtil.getCreateQrFile(content, basePath + path);
        //String name, String path, byte[] content, String scene
        try {
            FileInputStream fis = new FileInputStream(file);
            FileVO fileVo = fileService.upload(file.getName(),null, IoUtil.readBytes(fis),null);
            fis.close();
            return fileVo.getUrl();
        } catch (IOException e) {
            e.printStackTrace();
        }
//        String prePath = domain+"/infra/file/"+configVO.getId()+"/get/";
//        return prePath + path;
        return null;
    }

    /**
     * 更新用户分销累计金额和分销次数
     */
    public void updateMemberDistribution(Long memberId, BigDecimal distributionAmount) {
        MemberDO twoMemberDO = memberMapper.selectById(memberId);
        if (ObjectUtil.isNotEmpty(twoMemberDO)) {
            UpdateWrapper<MemberDO> memberUpdateWrapper = new UpdateWrapper<>();
            memberUpdateWrapper.eq("id", twoMemberDO.getId());
            //分销佣金（一级分销和二级分销的总数）
            memberUpdateWrapper.set("distribution_amount", Convert.toBigDecimal(twoMemberDO.getDistributionAmount(),BigDecimal.ZERO).add(distributionAmount));
            //分销笔数（一级分销和二级分销的总数）
            memberUpdateWrapper.set("distribution_number", twoMemberDO.getDistributionNumber() + 1);
            memberUpdateWrapper.set("wallet_amount", Convert.toBigDecimal(twoMemberDO.getWalletAmount(),BigDecimal.ZERO).add(distributionAmount));
            memberMapper.update(new MemberDO(), memberUpdateWrapper);
        }
    }
    private GroupPurchaseGoodsItemVO getGroupPurchaseGoodsItemInfo(Long goodsId,Integer number) {
        //GroupPurchaseGoodsItemDO, GroupPurchaseGoodsItemVO
        QueryWrapper<GroupPurchaseGoodsItemDO> wrapper = Wrappers.query();
        wrapper.eq("group_purchase_goods_id",goodsId);
        if(number.equals(1)){
            wrapper.orderByAsc(" constitute_number");
        }else{
            wrapper.le("constitute_number",number);
            wrapper.orderByDesc(" constitute_number");
        }
        wrapper.last(" limit 1");
        List<GroupPurchaseGoodsItemVO> goodsItemVOS = groupPurchaseGoodsItemMapper.selectVoList(wrapper);
        if(goodsItemVOS!=null && goodsItemVOS.size()>0){
            GroupPurchaseGoodsItemVO vo = goodsItemVOS.get(0);
            List<GroupPurchaseGoodsItemWxVO> list =  groupPurchaseGoodsItemMapper.selectVoList(wrapper,GroupPurchaseGoodsItemWxVO.class);
            return vo;
        }else{
            return null;
        }

    }

   private Boolean groupIsFull(Long groupPurchaseId,Long groupPurchaseGoodsId){
        //查询最大参团人数
       QueryWrapper<GroupPurchaseGoodsItemDO> wrapper = Wrappers.query();
       wrapper.eq("group_purchase_goods_id",groupPurchaseGoodsId);
       wrapper.orderByDesc(" constitute_number");
       wrapper.last(" limit 1");
       GroupPurchaseGoodsItemDO goodsItemDO = groupPurchaseGoodsItemMapper.selectOne(wrapper);
       int maxNumber = 0;
       if(ObjectUtil.isNotEmpty(goodsItemDO)){
           maxNumber = goodsItemDO.getConstituteNumber();
       }
       //查询已参团人数
       QueryWrapper<MemberGroupPurchaseItemDO> wrapper1 = Wrappers.query();
       wrapper.eq("group_purchase_id",groupPurchaseId);
       wrapper.eq("is_nullify",0);
       Long personNumber = memberGroupPurchaseItemMapper.selectCount(wrapper1);
       return personNumber.intValue()<maxNumber;
   }

    /**
     * 核销的分销明细
     * @param orderDO
     */
    private void verificationDistribution(OrderDO orderDO){
        /**
         * 处理明细记录
         */
        List<OrderTradeRecordDO> tradeRecordList = new ArrayList<>();

        /**
         * 删除待结算的订单交易记录
         */
        orderTradeRecordMapper.delete(new LambdaQueryWrapper<OrderTradeRecordDO>()
            .eq(OrderTradeRecordDO::getOrderId,orderDO.getId()).eq(OrderTradeRecordDO::getSettlementStatus,1));

        // 收入-全额
        OrderTradeRecordDO amountTradeRecord = new OrderTradeRecordDO();
        amountTradeRecord.setOrderId(orderDO.getId());
        amountTradeRecord.setFundType("order_settled");
        amountTradeRecord.setTradeAmount(orderDO.getRealityPayAmount());
        amountTradeRecord.setMemberId(orderDO.getMemberId());
        amountTradeRecord.setMemberWxUserId(orderDO.getMemberWxUserId());
        amountTradeRecord.setSettlementStatus(2);
        amountTradeRecord.setUserId(orderDO.getUserId());
        tradeRecordList.add(amountTradeRecord);
        // 手续费
        OrderTradeRecordDO commissionTradeRecord = new OrderTradeRecordDO();
        commissionTradeRecord.setOrderId(orderDO.getId());
        commissionTradeRecord.setFundType("charge_deduction");
        commissionTradeRecord.setTradeAmount(orderDO.getCommission().negate());
        commissionTradeRecord.setMemberId(orderDO.getMemberId());
        commissionTradeRecord.setMemberWxUserId(orderDO.getMemberWxUserId());
        commissionTradeRecord.setSettlementStatus(2);
        commissionTradeRecord.setUserId(orderDO.getUserId());
        tradeRecordList.add(commissionTradeRecord);
        // 分销佣金（一级）
        Long twoShareRecordId =0L;
        //查询分享记录
        if (orderDO.getOneDistributionAmount() != null && orderDO.getOneDistributionAmount().compareTo(BigDecimal.ZERO) == 1) {
            OrderTradeRecordDO oneDistributionTradeRecord = new OrderTradeRecordDO();
            oneDistributionTradeRecord.setOrderId(orderDO.getId());
            oneDistributionTradeRecord.setFundType("invite_deduction");
            oneDistributionTradeRecord.setTradeAmount(orderDO.getOneDistributionAmount().negate());
            oneDistributionTradeRecord.setMemberId(orderDO.getMemberId());
            oneDistributionTradeRecord.setMemberWxUserId(orderDO.getMemberWxUserId());
            oneDistributionTradeRecord.setSettlementStatus(2);
            oneDistributionTradeRecord.setUserId(orderDO.getUserId());
            tradeRecordList.add(oneDistributionTradeRecord);
        }
        // 分销佣金（二级）
        if (orderDO.getTwoDistributionAmount() != null && orderDO.getTwoDistributionAmount().compareTo(BigDecimal.ZERO) == 1) {
            OrderTradeRecordDO twoDistributionTradeRecord = new OrderTradeRecordDO();
            twoDistributionTradeRecord.setOrderId(orderDO.getId());
            twoDistributionTradeRecord.setFundType("invite_deduction");
            twoDistributionTradeRecord.setTradeAmount(orderDO.getTwoDistributionAmount().negate());
            twoDistributionTradeRecord.setMemberId(orderDO.getMemberId());
            twoDistributionTradeRecord.setMemberWxUserId(orderDO.getMemberWxUserId());
            twoDistributionTradeRecord.setSettlementStatus(2);
            twoDistributionTradeRecord.setUserId(orderDO.getUserId());
            tradeRecordList.add(twoDistributionTradeRecord);
        }
        orderTradeRecordMapper.insertBatch(tradeRecordList);

    }
}
